<template>
  <div class="dashboard-container">
    <!-- 页面标题和更新时间 -->
    <div class="dashboard-header">
      <div class="header-content">
        <h1 class="page-title">系统首页</h1>
        <div class="header-actions">
          <div class="update-time">
            <el-icon><Clock /></el-icon>
            <span>更新时间：{{ updateTime }}</span>
          </div>
          <el-button 
            type="primary" 
            :icon="Refresh" 
            :loading="isLoading"
            @click="refreshData"
            size="small"
          >
            刷新数据
          </el-button>
          <el-button 
            :icon="isDarkMode ? Sunny : Moon" 
            @click="toggleTheme"
            size="small"
            circle
          />
        </div>
      </div>
    </div>

    <!-- 数据统计卡片区域 -->
    <div class="stats-cards">
      <div class="card-row">
        <!-- 访客数卡片 -->
        <el-card class="stat-card visitor-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">访客数</div>
              <div class="card-value">{{ formatNumber(statsData.visitors) }}</div>
              <div class="card-trend up">
                <span class="trend-text">↑ {{ statsData.visitorTrend }}%</span>
              </div>
              <div class="card-comparison">
                <span class="comparison-item">同比: +{{ Math.floor(Math.random() * 20) }}%</span>
                <span class="comparison-item">环比: +{{ Math.floor(Math.random() * 15) }}%</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 付费用户数卡片 -->
        <el-card class="stat-card paid-user-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Avatar /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">付费用户数</div>
              <div class="card-value">{{ formatNumber(statsData.paidUsers) }}</div>
              <div class="card-trend up">
                <span class="trend-text">↑ {{ statsData.paidUserTrend }}%</span>
              </div>
              <div class="card-comparison">
                <span class="comparison-item">同比: +{{ Math.floor(Math.random() * 25) }}%</span>
                <span class="comparison-item">环比: +{{ Math.floor(Math.random() * 18) }}%</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 浏览量卡片 -->
        <el-card class="stat-card pageview-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><View /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">浏览量</div>
              <div class="card-value">{{ formatNumber(statsData.pageviews) }}</div>
              <div class="card-trend up">
                <span class="trend-text">↑ {{ statsData.pageviewTrend }}%</span>
              </div>
              <div class="card-comparison">
                <span class="comparison-item">同比: +{{ Math.floor(Math.random() * 30) }}%</span>
                <span class="comparison-item">环比: +{{ Math.floor(Math.random() * 12) }}%</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 支付订单数卡片 -->
        <el-card class="stat-card order-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">支付订单数</div>
              <div class="card-value">{{ formatNumber(statsData.orders) }}</div>
              <div class="card-trend up">
                <span class="trend-text">↑ {{ statsData.orderTrend }}%</span>
              </div>
              <div class="card-comparison">
                <span class="comparison-item">同比: +{{ Math.floor(Math.random() * 22) }}%</span>
                <span class="comparison-item">环比: +{{ Math.floor(Math.random() * 16) }}%</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 支付金额卡片 -->
        <el-card class="stat-card payment-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">支付金额</div>
              <div class="payment-details">
                <div class="payment-item">
                  <span class="payment-label">今日</span>
                  <span class="payment-value">¥{{ formatNumber(statsData.todayPayment) }}</span>
                </div>
                <div class="payment-item">
                  <span class="payment-label">昨日</span>
                  <span class="payment-value">¥{{ formatNumber(statsData.yesterdayPayment) }}</span>
                </div>
                <div class="payment-comparison">
                  <span class="comparison-item">同比: +{{ Math.floor(Math.random() * 35) }}%</span>
                  <span class="comparison-item">环比: +{{ Math.floor(Math.random() * 20) }}%</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="chart-section">
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="chart-header">
            <div class="chart-title-section">
              <span class="chart-title">支付金额对比</span>
              <el-select v-model="selectedTimeRange" @change="onTimeRangeChange" size="small" style="width: 120px;">
                <el-option label="今日" value="today"></el-option>
                <el-option label="昨日" value="yesterday"></el-option>
                <el-option label="本周" value="week"></el-option>
                <el-option label="本月" value="month"></el-option>
              </el-select>
            </div>
            <div class="chart-legend">
              <div class="legend-item">
                <div class="legend-color today"></div>
                <span>{{ getCurrentLabel() }}</span>
              </div>
              <div class="legend-item">
                <div class="legend-color yesterday"></div>
                <span>{{ getPreviousLabel() }}</span>
              </div>
            </div>
          </div>
        </template>
        <div class="chart-container">
          <div class="line-chart">
            <div class="chart-summary">
              <div class="summary-item">
                <span class="summary-label">今日支付金额(元)</span>
                <span class="summary-value">¥{{ formatNumber(statsData.todayPayment) }}</span>
              </div>
              <div class="summary-item">
                <span class="summary-label">昨日支付金额(元)</span>
                <span class="summary-value">¥{{ formatNumber(statsData.yesterdayPayment) }}</span>
              </div>
            </div>
            <div class="chart-svg">
              <svg viewBox="0 0 800 200" class="line-chart-svg">
                <!-- 网格线 -->
                <defs>
                  <pattern id="grid" width="40" height="20" patternUnits="userSpaceOnUse">
                    <path d="M 40 0 L 0 0 0 20" fill="none" stroke="#f0f0f0" stroke-width="1"/>
                  </pattern>
                </defs>
                <rect width="100%" height="100%" fill="url(#grid)" />
                
                <!-- Y轴标签 -->
                <text x="10" y="20" class="axis-label">50000</text>
                <text x="10" y="60" class="axis-label">40000</text>
                <text x="10" y="100" class="axis-label">30000</text>
                <text x="10" y="140" class="axis-label">20000</text>
                <text x="10" y="180" class="axis-label">10000</text>
                <text x="10" y="200" class="axis-label">0</text>
                
                <!-- X轴标签 -->
                <text x="50" y="195" class="axis-label">00</text>
                <text x="100" y="195" class="axis-label">02</text>
                <text x="150" y="195" class="axis-label">04</text>
                <text x="200" y="195" class="axis-label">06</text>
                <text x="250" y="195" class="axis-label">08</text>
                <text x="300" y="195" class="axis-label">10</text>
                <text x="350" y="195" class="axis-label">12</text>
                <text x="400" y="195" class="axis-label">14</text>
                <text x="450" y="195" class="axis-label">16</text>
                <text x="500" y="195" class="axis-label">18</text>
                <text x="550" y="195" class="axis-label">20</text>
                <text x="600" y="195" class="axis-label">22</text>
                
                <!-- 今日支付金额线 -->
                <polyline
                  :points="getTodayLinePoints()"
                  fill="none"
                  stroke="#4A90E2"
                  stroke-width="3"
                  class="line-today"
                />
                
                <!-- 昨日支付金额线 -->
                <polyline
                  :points="getYesterdayLinePoints()"
                  fill="none"
                  stroke="#FF8C00"
                  stroke-width="3"
                  class="line-yesterday"
                />
              </svg>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { 
  Clock, 
  User, 
  Avatar, 
  View, 
  ShoppingCart, 
  Money,
  Refresh,
  Moon,
  Sunny
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

// 响应式数据
const updateTime = ref(dayjs().format('YYYY/MM/DD HH:mm'))
const isLoading = ref(false)
const selectedTimeRange = ref('today')
const isDarkMode = ref(false)

// 统计数据
const statsData = reactive({
  visitors: 126560,
  visitorTrend: 12,
  paidUsers: 26560,
  paidUserTrend: 6,
  pageviews: 465600,
  pageviewTrend: 5,
  orders: 5600,
  orderTrend: 8,
  todayPayment: 610000,
  yesterdayPayment: 549000
})

// 格式化数字，添加千分位分隔符
const formatNumber = (num) => {
  return num.toLocaleString()
}

// 计算柱状图高度
const getBarHeight = (value) => {
  const maxValue = Math.max(statsData.todayPayment, statsData.yesterdayPayment)
  return `${(value / maxValue) * 200}px`
}

// 生成24小时支付数据
const generate24HourData = () => {
  const hours = Array.from({ length: 24 }, (_, i) => i)
  
  // 今日数据 - 模拟真实支付模式
  const todayData = hours.map(hour => {
    let baseAmount = 10000
    // 凌晨2-6点较低
    if (hour >= 2 && hour <= 6) {
      baseAmount = 5000 + Math.random() * 5000
    }
    // 上午8-12点较高
    else if (hour >= 8 && hour <= 12) {
      baseAmount = 20000 + Math.random() * 15000
    }
    // 下午14-18点中等
    else if (hour >= 14 && hour <= 18) {
      baseAmount = 15000 + Math.random() * 10000
    }
    // 晚上19-22点较高
    else if (hour >= 19 && hour <= 22) {
      baseAmount = 25000 + Math.random() * 20000
    }
    // 其他时间
    else {
      baseAmount = 8000 + Math.random() * 7000
    }
    return Math.floor(baseAmount)
  })
  
  // 昨日数据 - 略有不同的模式
  const yesterdayData = hours.map(hour => {
    let baseAmount = 10000
    // 凌晨0-4点较高（夜猫子模式）
    if (hour >= 0 && hour <= 4) {
      baseAmount = 20000 + Math.random() * 15000
    }
    // 上午6-10点较低
    else if (hour >= 6 && hour <= 10) {
      baseAmount = 8000 + Math.random() * 7000
    }
    // 下午12-16点中等
    else if (hour >= 12 && hour <= 16) {
      baseAmount = 12000 + Math.random() * 8000
    }
    // 晚上18-22点较高
    else if (hour >= 18 && hour <= 22) {
      baseAmount = 18000 + Math.random() * 12000
    }
    // 其他时间
    else {
      baseAmount = 6000 + Math.random() * 6000
    }
    return Math.floor(baseAmount)
  })
  
  return { todayData, yesterdayData }
}

// 获取今日线型图数据点
const getTodayLinePoints = () => {
  const { todayData } = generate24HourData()
  return todayData.map((value, index) => {
    const x = 50 + index * 25 // 每2小时一个点
    const y = 200 - (value / 50000) * 180 // 转换为SVG坐标
    return `${x},${y}`
  }).join(' ')
}

// 获取昨日线型图数据点
const getYesterdayLinePoints = () => {
  const { yesterdayData } = generate24HourData()
  return yesterdayData.map((value, index) => {
    const x = 50 + index * 25 // 每2小时一个点
    const y = 200 - (value / 50000) * 180 // 转换为SVG坐标
    return `${x},${y}`
  }).join(' ')
}

// 获取当前时间范围标签
const getCurrentLabel = () => {
  const labels = {
    today: '今日',
    yesterday: '昨日',
    week: '本周',
    month: '本月'
  }
  return labels[selectedTimeRange.value] || '今日'
}

// 获取对比时间范围标签
const getPreviousLabel = () => {
  const labels = {
    today: '昨日',
    yesterday: '前日',
    week: '上周',
    month: '上月'
  }
  return labels[selectedTimeRange.value] || '昨日'
}

// 时间范围变化处理
const onTimeRangeChange = (value) => {
  // 这里可以根据选择的时间范围重新获取数据
  console.log('时间范围变化:', value)
  // 可以调用API获取对应时间范围的数据
}

// 主题切换功能
const toggleTheme = () => {
  isDarkMode.value = !isDarkMode.value
  // 保存主题设置到本地存储
  localStorage.setItem('dashboardTheme', isDarkMode.value ? 'dark' : 'light')
  // 应用主题到body
  document.body.classList.toggle('dark-theme', isDarkMode.value)
  ElMessage.success(isDarkMode.value ? '已切换到暗色主题' : '已切换到亮色主题')
}

// 更新时间的定时器
let timeInterval = null

// 刷新数据函数
const refreshData = async () => {
  isLoading.value = true
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新数据（这里可以调用真实的API）
    // 模拟数据变化
    statsData.visitors += Math.floor(Math.random() * 1000)
    statsData.paidUsers += Math.floor(Math.random() * 100)
    statsData.pageviews += Math.floor(Math.random() * 5000)
    statsData.orders += Math.floor(Math.random() * 50)
    statsData.todayPayment += Math.floor(Math.random() * 10000)
    
    // 更新时间
    updateTime.value = dayjs().format('YYYY/MM/DD HH:mm')
    
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  console.log('Dashboard页面已加载')
  
  // 加载保存的主题设置
  const savedTheme = localStorage.getItem('dashboardTheme')
  if (savedTheme === 'dark') {
    isDarkMode.value = true
    document.body.classList.add('dark-theme')
  }
  
  // 每分钟更新时间
  timeInterval = setInterval(() => {
    updateTime.value = dayjs().format('YYYY/MM/DD HH:mm')
  }, 60000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.dashboard-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 24px;
  border-radius: 12px;
  color: white;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  margin: 0;
}

.update-time {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  opacity: 0.9;
}

.stats-cards {
  margin-bottom: 24px;
}

.card-row {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.card-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0.1;
}

/* 访客数卡片 - 更亮的蓝色背景 */
.visitor-card {
  background: linear-gradient(135deg, #4A90E2 0%, #7BB3F0 100%);
}

.visitor-card .card-content::before {
  display: none;
}

/* 付费用户数卡片 - 更亮的绿色背景 */
.paid-user-card {
  background: linear-gradient(135deg, #50C878 0%, #7ED321 100%);
}

.paid-user-card .card-content::before {
  display: none;
}

/* 浏览量卡片 - 更亮的橙色背景 */
.pageview-card {
  background: linear-gradient(135deg, #FF8C00 0%, #FFA500 100%);
}

.pageview-card .card-content::before {
  display: none;
}

/* 订单数卡片 - 更亮的紫色背景 */
.order-card {
  background: linear-gradient(135deg, #8A2BE2 0%, #BA55D3 100%);
}

.order-card .card-content::before {
  display: none;
}

/* 支付金额卡片 - 更亮的粉色背景 */
.payment-card {
  background: linear-gradient(135deg, #FF69B4 0%, #FFB6C1 100%);
}

.payment-card .card-content::before {
  display: none;
}

.card-icon {
  font-size: 32px;
  color: white;
  margin-right: 16px;
  position: relative;
  z-index: 1;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
}

.card-info {
  flex: 1;
  position: relative;
  z-index: 1;
}

.card-title {
  color: white;
  font-size: 14px;
  margin-bottom: 8px;
  opacity: 0.95;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.card-value {
  color: white;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.card-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.card-trend.up {
  color: #52c41a;
}

.card-trend.down {
  color: #ff4d4f;
}

.trend-text {
  color: inherit;
}

.card-comparison {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-top: 4px;
}

.comparison-item {
  font-size: 10px;
  color: white;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.payment-comparison {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-top: 8px;
}

.payment-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.payment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.payment-label {
  color: white;
  font-size: 12px;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.payment-value {
  color: white;
  font-size: 16px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.chart-section {
  margin-top: 24px;
}

.chart-card {
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.chart-legend {
  display: flex;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #666;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-color.today {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.legend-color.yesterday {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.chart-container {
  height: 400px;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.line-chart {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chart-summary {
  display: flex;
  justify-content: space-around;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.summary-label {
  font-size: 14px;
  color: #666;
}

.summary-value {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.chart-svg {
  flex: 1;
  width: 100%;
  min-height: 250px;
}

.line-chart-svg {
  width: 100%;
  height: 100%;
}

.axis-label {
  font-size: 12px;
  fill: #666;
  font-family: Arial, sans-serif;
}

.line-today {
  stroke: #4A90E2;
  stroke-width: 3;
  fill: none;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.line-yesterday {
  stroke: #FF8C00;
  stroke-width: 3;
  fill: none;
  stroke-linecap: round;
  stroke-linejoin: round;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .card-row {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .chart-title-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

@media (max-width: 768px) {
  .card-row {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .header-content {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .chart-title-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .chart-container {
    height: 350px;
  }
  
  .chart-summary {
    flex-direction: column;
    gap: 10px;
  }
  
  .card-comparison {
    display: none; /* 在小屏幕上隐藏对比数据以节省空间 */
  }
  
  .payment-comparison {
    display: none;
  }
}

@media (max-width: 480px) {
  .card-row {
    grid-template-columns: 1fr;
  }
  
  .dashboard-container {
    padding: 16px;
  }
  
  .header-content {
    padding: 16px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .chart-container {
    height: 300px;
  }
  
  .chart-summary {
    padding: 15px;
  }
  
  .summary-value {
    font-size: 16px;
  }
  
  .card-content {
    padding: 16px;
  }
  
  .card-value {
    font-size: 20px;
  }
}

/* 暗色主题样式 */
:global(.dark-theme) .dashboard-container {
  background-color: #1a1a1a;
  color: #e0e0e0;
}

:global(.dark-theme) .chart-card {
  background-color: #2d2d2d;
  border: 1px solid #404040;
}

:global(.dark-theme) .chart-title {
  color: #e0e0e0;
}

:global(.dark-theme) .legend-item span {
  color: #b0b0b0;
}

:global(.dark-theme) .bar-value {
  color: #e0e0e0;
}

:global(.dark-theme) .bar-label {
  color: #b0b0b0;
}
</style>

